<?php
include "class.paypal.recurring.php";
require_once('functions/pageLoad.php');
$obj=new paypal_recurring;

if(isset($_GET['plan_type'])){
	$sql = "SELECT cost FROM subscriptions WHERE id = '".mysql_real_escape_string($_GET['plan_type'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$_SESSION['amt'] = $rs['cost'];
	$_SESSION['plan_type'] = $_GET['plan_type'];
}

$obj->environment = 'live';	// or 'beta-sandbox' or 'live'
$obj->paymentType = urlencode('Authorization');				// or 'Sale' or 'Order'

// Set request-specific fields.
$obj->startDate = urlencode(date("c"));
$obj->billingPeriod = urlencode("Year");				// or "Day", "Week", "SemiMonth", "Year"
$obj->billingFreq = urlencode("1");						// combination of this and billingPeriod must be at most a year
$obj->paymentAmount = urlencode($_SESSION['amt']);
$obj->currencyID = urlencode('GBP');							// or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

/* PAYPAL API  DETAILS */
$obj->API_UserName = urlencode($settings['paypal_api_username']);
$obj->API_Password = urlencode($settings['paypal_api_password']);
$obj->API_Signature = urlencode($settings['paypal_api_signature']);
$obj->API_Endpoint = "https://api-3t.paypal.com/nvp";

/*SET SUCCESS AND FAIL URL*/
$obj->returnURL = urlencode("http://".$settings['domain_name']."/registration_payment.php?complete=true");
$obj->cancelURL = urlencode("http://".$settings['domain_name']."/my-account");

if(!isset($_GET['complete'])){
	$obj->setExpressCheckout();
}

else{
	$result = $obj->getExpressCheckout();
	
	if($result['status'] == 'success'){

	// update active & subscription expiration
	$user_id = explode("_", $_SESSION['user']);
	$sql = "UPDATE tradesman SET active = 1, subscription_expiration = '".date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")+1))."', paypal_profile_id = '".mysql_real_escape_string($result['profile_id'])."', subscription_id = '".mysql_real_escape_string($_SESSION['plan_type'])."' WHERE user_id = '".$user_id[0]."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	
	// insert payment
	$sql = "SELECT id FROM tradesman WHERE user_id = '".mysql_real_escape_string($user_id[0])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);

	$payment_sql = "INSERT INTO payments SET user_id = '".mysql_real_escape_string($user_id[0])."', tradesman_id = '".$rs['id']."', payment_type = '2', amount = '".$_SESSION['amt']."', ip_address = '".$_SERVER['REMOTE_ADDR']."', payment_made = NOW()";
	$payment_query=mysql_query( $payment_sql ) or die ("Error in query: $payment_sql . " . mysql_error());	

	header("Location: /my-account?confirm=true");
	
	}
	
	else{
	
	header("Location: /my-account");
	
	}

}

?>